package com.helloapp.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 权限过滤器
 */
@WebFilter("/*")
public class LoginFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//System.out.println("Filter");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		//URL地址
		String method = req.getRequestURI();
		System.out.println(method);
		if(method!=null && (method.contains("login")||method.contains("register")||method.contains("zhou"))){
			chain.doFilter(request, response);
			return;
		}
		
		String username = (String)session.getAttribute("username");
		if(username !=null){
			System.out.println("username = " + username);
			chain.doFilter(request, response);
		}else{ // 没有登录，需要中转到登录页面
			((HttpServletResponse)response).sendRedirect("login2.jsp");
			
		}
	}

	@Override
	public void destroy() {
	
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	
	}


}
